﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Ext.Net;
using WEB.Core.Controls;
using WEB.Core.Util;
using log4net;
using WEB.BLL.Entities;
using WEB.BLL.Services;
using System.IO;
using System.Text.RegularExpressions;
using WEB.BLL;
using System.Data;
using System.Data.OleDb;
using System.Globalization;

namespace WEB.APP.Modules.List
{
    public partial class ImportStudent : BasePage, IBaseListPage
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ImportStudent));
        public ImportStudent()
            : base(SCREENS.IMPORTSTUDENT, false)
        {

        }

        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            btnResetAll.Hidden = !IsDelete;
        }

        protected void btnResetAll_Click(object sender, DirectEventArgs e)
        {
            X.Msg.Show(new MessageBoxConfig
            {
                Title = "Warning !!!",
                Message = "This function will permanently remove all information about students and projects.<br/><b>The data can not be restored after this step.</b><br/>Please enter the password if you want to perform this task.",
                Icon = MessageBox.Icon.WARNING,
                Prompt = true,
                Buttons = MessageBox.Button.OKCANCEL,
                Fn = new JFunction { Handler = "if(arguments[0] === 'ok'){ MethodNamespace.RemoveAll(arguments[1]); }" }
            });
        }


        [DirectMethod]
        public void RemoveAll(string Password)
        {
            try
            {
                UserEntity _ett = new UserEntity() { UserName = CurrentUser.UserName };
                _ett = UserService.GetInstance().LoadByPrimaryKey(_ett);
                if (!_ett.Password.ToLower().Equals(Encryption.StringToMD5Hash(Password).ToLower()))
                {
                    Msg.Error("Password is incorrect");
                    return;
                }
                StudentService.GetInstance().DeleteAll();
                Msg.Informational("All data of students and projects are deleted.");
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }

        [DirectMethod]
        public void UploadClick()
        {
            try
            {
                if (this.flUpload.HasFile)
                {
                    HttpPostedFile myFile = flUpload.PostedFile;
                    if ("application/octet-stream".Equals(myFile.ContentType) || "application/vnd.ms-excel".Equals(myFile.ContentType))
                    {
                        int nFileLen = myFile.ContentLength;
                        byte[] myData = new byte[nFileLen];
                        myFile.InputStream.Read(myData, 0, nFileLen);
                        string strFilename = Path.GetFileName(myFile.FileName);
                        string strURL = Server.MapPath("~/UploadFile/" + strFilename);
                        WriteToFile(strURL, ref myData);
                        hdURLFile.Value = strURL;
                    }
                    else
                    {
                        X.Msg.Alert("Notice", "Please select the *.csv file.").Show();
                        return;
                    }

                }
                else
                {
                    X.Msg.Alert("Notice", "Please select the *.csv file.").Show();
                }
            }
            catch (Exception ex)
            {
                X.Msg.Alert("Notice", "Error read file").Show();
                Notification(ex.Message);
            }

        }
        protected void storeMain_OnRefreshData(object sender, StoreRefreshDataEventArgs e)
        {
            try
            {
                List<StudentEntity> lstImport = new List<StudentEntity>();
                StudentService StudentS = StudentService.GetInstance();
                var lstStudent = ReadFile(hdURLFile.Value.ToString());
                if (lstStudent == null) return;
                foreach (var item in lstStudent)
                {
                    StudentEntity StudentE = new StudentEntity();
                    StudentE = StudentS.LoadByPrimaryKey(item);
                    if (StudentE != null)
                    {
                        item.StatusImport = true;
                    }
                    lstImport.Add(item);
                }
                if (lstImport.Count > 0)
                {

                    storeMain.DataSource = lstImport;
                    storeMain.DataBind();
                }
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }

        private void WriteToFile(string strPath, ref byte[] Buffer)
        {
            // Create a file
            if (File.Exists(strPath))
            {
                File.Delete(strPath);
            }
            FileStream newFile = new FileStream(strPath, FileMode.Create);
            newFile.Write(Buffer, 0, Buffer.Length);
            newFile.Close();

        }
        [DirectMethod]
        public void SaveData(string jsonData)
        {
            try
            {
                if (string.IsNullOrEmpty(jsonData))
                {
                    X.Msg.Alert("Notice", "Please select the Import Data!").Show();
                    return;
                }
                StudentService StudentS = StudentService.GetInstance();
                List<StudentEntity> lstJson = new List<StudentEntity>();
                lstJson = JSON.Deserialize<List<StudentEntity>>(jsonData);
                if (lstJson.Count <= 0)
                {
                    X.Msg.Alert("Notice", "Please check to Import Data!").Show();
                    return;
                }
                foreach (var item in lstJson)
                {
                    if (item.StatusImport != true)
                        StudentS.Insert(item);
                    else
                    {
                        StudentS.Update(item);
                    }
                }
                X.Msg.Alert("Notice", "Import data success");
            }
            catch (Exception ex)
            {
                X.Msg.Alert("Notice", "Import data fail");
                Notification(ex);
            }

        }

        private static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
        {
            string header = isFirstRowHeader ? "Yes" : "No";

            string pathOnly = Path.GetDirectoryName(path);
            string fileName = Path.GetFileName(path);

            string sql = String.Format(@"SELECT * FROM [{0}]", fileName);

            using (OleDbConnection connection = new OleDbConnection(String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Text;HDR={1}""", pathOnly, header)))
            using (OleDbCommand command = new OleDbCommand(sql, connection))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
            {
                DataTable dataTable = new DataTable() { Locale = CultureInfo.CurrentCulture };
                adapter.Fill(dataTable);
                return dataTable;
            }
        }


        private List<StudentEntity> ReadFile(string FileName)
        {
            try
            {
                if (!File.Exists(FileName))
                {
                    X.Msg.Alert("Notice", string.Format("{0} File does not exists. Please select the *.csv file.", FileName)).Show();
                    return new List<StudentEntity>();
                }
                List<StudentEntity> lstStudent = new List<StudentEntity>();
                foreach (DataRow _Row in GetDataTableFromCsv(FileName, true).Rows)
                {
                    StudentEntity StudentE = new StudentEntity()
                    {
                        StudentId = Util.Obj2Long(_Row["Person Id"]),
                        LocationId = Util.SafeTrim(_Row["Location Cd"]),
                        Sex = Util.SafeTrim(_Row["Sex"]) == "M" ? true : false,
                        BirthDt = Util.Str2DataTime(_Row["Birth Dt"].ToString()),
                        HomeLang = Util.SafeTrim(_Row["Home Language"]),
                        CourseId = Util.Obj2Decimal(_Row["Course Cd"]),
                        CourseTitle = Util.SafeTrim(_Row["Course Title"]),
                        SurName = Util.SafeTrim(_Row["Surname"]),
                        GivenName = Util.SafeTrim(_Row["Given Names"]),
                        Addr1 = Util.SafeTrim(_Row["Addr Line 1"]),
                        ComYr = Util.Obj2Decimal(_Row["Commencement Yr"]),
                        UaiYr = Util.Obj2Decimal(_Row["Uai Yr"]),
                        Uai = Util.Obj2Decimal(_Row["Uai"]),
                        Gpa = Util.Obj2Int(_Row["Gpa"]),
                        CreditPass = Util.Obj2Int(_Row["Credit Pts Passed"]),
                        EmailAddr = Util.SafeTrim(_Row["Email Addr"]),
                        AustPostcode = Util.Obj2Decimal(_Row["Aust Postcode"]),
                        Citizenship = Util.SafeTrim(_Row["Citizenship"]),
                        CitizenshipStatus = Util.SafeTrim(_Row["Citizenship Status"])
                    };
                    if (Util.SafeTrim(_Row["Addr Line 2"]).ToLower() != "null")
                        StudentE.Addr2 = Util.SafeTrim(_Row["Addr Line 2"]);
                    if (Util.SafeTrim(_Row["Addr Line 3"]).ToLower() != "null")
                        StudentE.Addr3 = Util.SafeTrim(_Row["Addr Line 3"]);
                    if (Util.SafeTrim(_Row["Addr Line 4"]).ToLower() != "null")
                        StudentE.Addr4 = Util.SafeTrim(_Row["Addr Line 4"]);
                    if (Util.SafeTrim(_Row["Addr Line 5"]).ToLower() != "null")
                        StudentE.Addr5 = Util.SafeTrim(_Row["Addr Line 5"]);
                    if (Util.SafeTrim(_Row["Home Phone"]).ToLower() != "null")
                        StudentE.HomePhone = Util.SafeTrim(_Row["Home Phone"]);
                    if (Util.SafeTrim(_Row["Work Phone"]).ToLower() != "null")
                        StudentE.WorkPhone = Util.SafeTrim(_Row["Work Phone"]);
                    if (Util.SafeTrim(_Row["Mobile"]).ToLower() != "null")
                        StudentE.Mobile = Util.SafeTrim(_Row["Mobile"]);
                    lstStudent.Add(StudentE);
	            }
                return lstStudent;
            }
            catch
            {
                X.Msg.Alert("Notice", "Wrong CSV File format").Show();
                return new List<StudentEntity>();
            }
        }


        protected void grdMain_OnCommand(object sender, DirectEventArgs e)
        {
            Sender = sender;
            E = e;
        }
        public void btnAdd_Click(object sender, DirectEventArgs e) { }
        public void btnEdit_Click(object sender, DirectEventArgs e) { }
        public void btnDelete_Click(object sender, DirectEventArgs e) { }
        public void btnPrint_Click(object sender, DirectEventArgs e) { }
        public void btnImport_Click(object sender, DirectEventArgs e) { }
        public void btnExport_Click(object sender, DirectEventArgs e) { }
        public void btnFind_Click(object sender, DirectEventArgs e) { }
        public object Sender { get; set; }
        public DirectEventArgs E { get; set; }
    }
}
